package com.hd.controller.activiti.util.cmd;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ExecutionEntityManager;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.task.Task;

import com.hd.controller.activiti.util.cmd.util.ShareniuLoopVariableUtils;
/**
 * 减签：删除指定任务数
 * @author hzhh123
 * 2018年8月17日下午1:12:52
 */
public class ShareniuCountersignMinCmd implements Command<Void> {
	protected String taskId;
	

	public ShareniuCountersignMinCmd(String taskId) {
		super();
		this.taskId = taskId;
	}


	@Override
	public Void execute(CommandContext commandContext) {
		ProcessEngineConfigurationImpl pec = commandContext.getProcessEngineConfiguration();
		RuntimeService runtimeService = pec.getRuntimeService();
		TaskService taskService=pec.getTaskService();
		Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
		TaskEntity taskEntity=(TaskEntity)task;
		//获取execution执行对象
		Execution execution = runtimeService.createExecutionQuery().executionId(task.getExecutionId()).singleResult();
		ExecutionEntity ee=(ExecutionEntity)execution;
		int loopCounter=ShareniuLoopVariableUtils.getLoopVariable(ee, "nrOfInstances");
		int nrOfCompletedInstances=ShareniuLoopVariableUtils.getLoopVariable(ee, "nrOfActiveInstances");
		ShareniuLoopVariableUtils.setLoopVariable(ee, "nrOfInstances", loopCounter-1);
		ShareniuLoopVariableUtils.setLoopVariable(ee, "nrOfActiveInstances", nrOfCompletedInstances-1);
		//45、46行解除ACT_RU_TASK与ACT_RU_EXECUTION表之间的数据依赖
		taskEntity.setProcessInstance(null);
		taskEntity.setExecutionId(null);
		//更新task会话缓存
		taskService.saveTask(taskEntity);
		ExecutionEntityManager executionEntityManager=commandContext.getExecutionEntityManager();
		executionEntityManager.deleteProcessInstance(execution.getId(), "减签", false);
		taskService.deleteTask(taskId,false);
		return null;
	}

}
